package com.laiyima.zhongjiang.linghuilv.demo.home;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.laiyima.zhongjiang.linghuilv.demo.R;
import com.laiyima.zhongjiang.linghuilv.demo.Serviceprovider.BanlanceDetActivity;
import com.laiyima.zhongjiang.linghuilv.demo.Serviceprovider.FreezeInfoActivity;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.CenterPopupView;

import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.math.BigDecimal;
import java.text.DecimalFormat;

import me.imid.swipebacklayout.lib.app.SwipeBackActivity;

public class BalanceActivity extends SwipeBackActivity implements View.OnClickListener {
    private LinearLayout imageView;
    private EditText inputmoney;
    private TextView textView, service_money, actual_receipt, tolook_banlancedetails, intfree,to_freeInfo;
    private String TAG = "BalanceActivity";
    private int balCode, qrCode, every;
    private Button balance_button;
    private Double withFee;
    private String s, p, e, Tips, reout,money_balance;
    private TextView deduction_of_individual, service_charge, banlance_service_charge;
    BigDecimal bg;

    protected boolean useThemestatusBarColor = false;//是否使用特殊的标题栏背景颜色，android5.0以上可以设置状态栏背景色，如果不使用则使用透明色值

    protected void setStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0及以上
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            //根据上面设置是否对状态栏单独设置颜色
            if (useThemestatusBarColor) {
                // getWindow().setStatusBarColor(getResources().getColor(R.color.colorTheme));
            } else {
                getWindow().setStatusBarColor(Color.TRANSPARENT);
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//android6.0以后可以对状态栏文字颜色和图标进行修改
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_balance);
        imageView = (LinearLayout) findViewById(R.id.balance_back);
        imageView.setOnClickListener(this);
        textView = (TextView) findViewById(R.id.show_balancemoeny);
        deduction_of_individual = (TextView) findViewById(R.id.deduction_of_individual);
        service_charge = (TextView) findViewById(R.id.service_charge);
        banlance_service_charge = (TextView) findViewById(R.id.banlance_service_charge);
        tolook_banlancedetails = (TextView) findViewById(R.id.tolook_banlancedetails);
        tolook_banlancedetails.setOnClickListener(this);

        balance_button = (Button) findViewById(R.id.balance_button);
        balance_button.setOnClickListener(this);
        to_freeInfo= (TextView) findViewById(R.id.to_freeInfo);
        to_freeInfo.setOnClickListener(this);
        service_money = (TextView) findViewById(R.id.service_money);
        actual_receipt = (TextView) findViewById(R.id.actual_receipt);
        inputmoney = (EditText) findViewById(R.id.inputmoney);
        intfree = (TextView) findViewById(R.id.intfree);
        inputmoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                s = inputmoney.getText().toString();

                if (!s.isEmpty() && s.length() >= 0) {
                    Integer a = Integer.parseInt(s);
                    Double d = a * withFee / 100 + every / 100;

                    Double j = a * withFee / 100;
                    DecimalFormat decimalFormat2 = new DecimalFormat("0.00");
                    String p1 = decimalFormat2.format(j);
                    service_charge.setText("本次扣除手续费:" + p1 + "元");
                    DecimalFormat decimalFormat = new DecimalFormat("0.00");
                    p = decimalFormat.format(d);

                    service_money.setText(p + "");
                    Double f = a - d;
                    e = decimalFormat.format(f);
                    actual_receipt.setText(e + "");

                }
                if (s.length() == 0) {
                    service_charge.setText("本次扣除手续费:0.00元");
                    actual_receipt.setText("0.00");
                    service_money.setText("0.00");
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        getwithFee();
        intView();
        setStatusBar();
    }

    private void intFree() {
        SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/lfl_api/Commonlfl/home_info");
        //需要带入的参数
        params.addBodyParameter("uid", userID);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    balCode = jsonObject.optInt("code", 0);
                    String data = jsonObject.optString("data", null);
                    JSONObject jsonObjec = new JSONObject(data);
                    String money = jsonObjec.optString("freeze", "");
                    Double d=Double.parseDouble(money);
                    DecimalFormat decimalFormat2 = new DecimalFormat("0.00");
                    String p2 = decimalFormat2.format(d);
                    intfree.setText(p2);

                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (balCode == 200) {

                }
                if (balCode == 500) {
                    Toast.makeText(getBaseContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }


    private void getwithFee() {
        SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/lfl_api/Commonlfl/withdrawal_rate");
        //需要带入的参数
        params.addBodyParameter("uid", userID);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    balCode = jsonObject.optInt("code", 0);
                    String data = jsonObject.optString("data", null);
                    if (!TextUtils.isEmpty(data)) {
                        JSONObject jsonObjec = new JSONObject(data);
                        every = jsonObjec.optInt("every", 0);
                        withFee = jsonObjec.optDouble("withFee", 0);
                        deduction_of_individual.setText("佣金提现扣除个人所得税:" + withFee + "%");

                        int k = every / 100;
                        DecimalFormat decimalFormat2 = new DecimalFormat("0.00");
                        String p2 = decimalFormat2.format(k);
                        banlance_service_charge.setText("本次提现扣除提现手续费:" + p2 + "元/笔");


                        Log.e(TAG, "withFee" + withFee + "every" + every);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (balCode == 200) {

                }
                if (balCode == 500) {
                    Toast.makeText(getBaseContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.to_freeInfo:
                Intent TIintent = new Intent(BalanceActivity.this, FreezeInfoActivity.class);
                startActivity(TIintent);
                break;

            case R.id.tolook_banlancedetails:
                Intent BBintent = new Intent(BalanceActivity.this, BanlanceDetActivity.class);
                startActivity(BBintent);
                break;
            case R.id.balance_back:
                finish();
                break;
            case R.id.balance_button:
                 if (inputmoney.getText().toString().length() == 0) {
                    Toast.makeText(getBaseContext().getApplicationContext(), "请输入金额", Toast.LENGTH_SHORT).show();
                }else {
                    dialog_show1();
                }

                break;
        }
    }


    private void dialog_show1() {
        BalanceActivity.CustomPopup1 customPopup = new BalanceActivity.CustomPopup1(this);
        new XPopup.Builder(this)
                .asCustom(customPopup)
                .show();
    }

    public class CustomPopup1 extends CenterPopupView {

        private TextView mytextView, banlance_resout;

        public CustomPopup1(@NonNull Context context) {
            super(context);
        }

        @Override
        protected int getImplLayoutId() {
            return R.layout.banlance_custom_popup;
        }

        @Override
        protected void onCreate() {
            super.onCreate();
            banlance_resout = findViewById(R.id.banlance_resout);
            banlance_resout.setText("请确认提现");
            mytextView = findViewById(R.id.balance_tishi);
            mytextView.setText("本次提现实际到帐金额:"+e+"元");
            findViewById(R.id.banlance_dialog_button).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                    toBalance();
                }
            });
        }

        protected void onShow() {
            super.onShow();
        }
    }


    private void dialog_show() {
        BalanceActivity.CustomPopup customPopup = new BalanceActivity.CustomPopup(this);
        new XPopup.Builder(this)
                .asCustom(customPopup)
                .show();
    }

    public class CustomPopup extends CenterPopupView {

        private TextView mytextView, banlance_resout;

        public CustomPopup(@NonNull Context context) {
            super(context);
        }

        @Override
        protected int getImplLayoutId() {
            return R.layout.banlance_custom_popup;
        }

        @Override
        protected void onCreate() {
            super.onCreate();
            banlance_resout = findViewById(R.id.banlance_resout);
            banlance_resout.setText(reout);
            mytextView = findViewById(R.id.balance_tishi);
            mytextView.setText(Tips);
            findViewById(R.id.banlance_dialog_button).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });
        }

        protected void onShow() {
            super.onShow();
        }
    }

    private void toBalance() {
        SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/lfl_api/Commonlfl/withdraw");
        //需要带入的参数
        params.addBodyParameter("uid", userID);
        params.addBodyParameter("account", e);
        params.addBodyParameter("money", s);
        params.addBodyParameter("fee", p);

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    balCode = jsonObject.optInt("code", 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (balCode == 200) {
                    Toast.makeText(getBaseContext().getApplicationContext(), "提现成功，预计到账时间为 1-15 分钟", Toast.LENGTH_SHORT).show();
                    Intent Balanceintent = new Intent(BalanceActivity.this, MyWalletActivity.class);
                    startActivity(Balanceintent);

                }
                if (balCode == 199) {
                    reout = "提现失败";
                    Tips = "请先绑定银行卡之后再进行提现";
                    dialog_show();

                    //Toast.makeText(getBaseContext().getApplicationContext(), "请先实名认证之后再进行提现", Toast.LENGTH_SHORT).show();
                }
                if (balCode == 206) {
                    reout = "提现失败";
                    Tips = "提现金额不能小于10元";
                    dialog_show();
                    //Toast.makeText(getBaseContext().getApplicationContext(), "提现金额不能小于10元", Toast.LENGTH_SHORT).show();
                }
                if (balCode == 207) {
                    reout = "提现失败";
                    Tips = "钱包余额不足";
                    dialog_show();
                    // Toast.makeText(getBaseContext().getApplicationContext(), "钱包余额不足", Toast.LENGTH_SHORT).show();
                }
                if (balCode == 201) {
                    reout = "提现失败";
                    Tips = "提现异常，请联系管理员";
                    dialog_show();
                    // Toast.makeText(getBaseContext().getApplicationContext(), "提现异常，请联系管理员", Toast.LENGTH_SHORT).show();
                }
                if (balCode == 202) {
                    reout = "提现失败";
                    Tips = "提现失败";
                    dialog_show();
                    // Toast.makeText(getBaseContext().getApplicationContext(), "提现失败", Toast.LENGTH_SHORT).show();
                }

                if (balCode == 500) {
                    reout = "提现失败";
                    Tips = "系统异常";
                    dialog_show();
                    // Toast.makeText(getBaseContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                }
                if (balCode == 189) {
                    reout = "提现失败";
                    Tips = "实际到账金额不能小于零";
                    dialog_show();
                    // Toast.makeText(getBaseContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });


    }

    private void intView() {
        SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/api/Wallet/balance");
        //需要带入的参数
        params.addBodyParameter("uid", userID);
        // params.addBodyParameter("captcha", captcha);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                try {
                    JSONObject jsonObject = new JSONObject(result);
                    balCode = jsonObject.optInt("code", 0);
                    money_balance = jsonObject.optString("money", "");
                    String money = money_balance + "";
                    SpannableString s = new SpannableString(money);//这里输入自己想要的提示文字

                    Double z = Double.parseDouble(money);
                    DecimalFormat decimalFormat = new DecimalFormat("0.00");
                    String x = decimalFormat.format(z);
                    bg=new BigDecimal(x);

                    inputmoney.setHint("可以转出金额为:" + bg + "元");
                    textView.setText(money);


                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (balCode == 200) {

                }
                if (balCode == 500) {
                    Toast.makeText(getBaseContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                intFree();
            }
        });
    }
}
